package com.epfresh.supplier.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.global.BuyerConstant;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.AgencyListActivity;
import com.epfresh.supplier.activity.BaseProductDetailActivity;
import com.epfresh.supplier.activity.BaseStoreInfoActivity;
import com.epfresh.supplier.activity.GrouponInfoActivity;
import com.epfresh.supplier.activity.HomeActivity;
import com.epfresh.supplier.adapter.HomeBuyerCityItemViewBinder;
import com.epfresh.supplier.adapter.HomeBuyerItemViewBinder;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.dialog.FilterCityDialog;
import com.epfresh.supplier.entity.AgencyListItem;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.Groupon;
import com.epfresh.supplier.entity.HomeBuyer;
import com.epfresh.supplier.entity.HomeBuyerNumber;
import com.epfresh.supplier.entity.MerChantInfo;
import com.epfresh.supplier.entity.MerchantMember;
import com.epfresh.supplier.entity.StaffInfo;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;

/**
 * Author: Chen
 * Date: 2018/6/28
 * Desc:
 */
public class PingCheJinHuoFragment extends BaseFragment {
    private List<Object> mItems = new ArrayList<>();
    private MultiTypeAdapter mMultiAdapter;
    private HomeBuyerItemViewBinder itemViewBinder;
    private HomeBuyerCityItemViewBinder itemBuyerCityViewBinder;
    private LinearLayoutManager mManager;
    private RecyclerView rv;
    private String storeId;//基地店铺id
    private LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();
    private LoadMoreViewBinder loadMoreViewBinder;
    private PtrFrameLayout ptrFrameLayout;
    private List<HomeBuyer> mHomeBuyers = new ArrayList<>();

    private boolean isLockAgency;
    public static boolean isCanRefresh = true;
    private int pageNum = -1;
    public String cityId = "", categoryId = "";

    @Override
    public String getBaseTag() {
        return Constant.TAG_HOME_FRAGMENT;
    }

    //刷新
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv, header) && isCanRefresh;
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            updateReqData();
            if (getAppActivity() instanceof HomeActivity) {
//                if (((HomeActivity) getAppActivity()).buyerFragmentNew != null) {
//                    ((HomeActivity)getAppActivity()).buyerFragmentNew.reqMerchantList();
//                }
            }
        }
    };

    //加载更多
    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing() && pageNum > -1;
        }

        @Override
        public void onLoadMore() {
            loadMoreDelegate.setStatusLoading();
            reqSupplyStoreDyn(pageNum + 1);
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home_buyer, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    /**
     * view 初始化
     */
    private void initView(View v) {
        ptrFrameLayout = v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);

        rv = v.findViewById(R.id.home_buyer_fragment_rv);
        mManager = new LinearLayoutManager(getContext());
        rv.setLayoutManager(mManager);
        mMultiAdapter = new MultiTypeAdapter();

        loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        loadMoreDelegate.attach(rv, loadMoreSubject);

        itemBuyerCityViewBinder = new HomeBuyerCityItemViewBinder();
        itemBuyerCityViewBinder.setOnBuyerListener(new HomeBuyerCityItemViewBinder.OnBuyerListener() {
            @Override
            public void onBuyer(View view, int position, Groupon data) {
                storeId = data.getBaseStoreId();
                 intoGrouponInfo(data.getGrouponId(), data.getProductId(), data);
            }
        });

        itemViewBinder = new HomeBuyerItemViewBinder();
        itemViewBinder.setOnBuyerListener(new HomeBuyerItemViewBinder.OnBuyerListener() {
            @Override
            public void onBuyer(View view, int position, HomeBuyer data) {
                storeId = data.getBaseStoreId();
                intoGrouponInfo(null, data.getId(), null);
            }
        });
        itemViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if (data instanceof HomeBuyer) {
                    switch (view.getId()) {
                        case R.id.rl_base:
                            HomeBuyer info = (HomeBuyer) data;
                            intoBaseStore(info.getBaseStoreId());
                            break;
                        case R.id.rl_product:
                            intoProductDetail((HomeBuyer) data);
                            break;
                    }
                }
            }
        });

        mMultiAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        mMultiAdapter.register(HomeBuyer.class, itemViewBinder);
        mMultiAdapter.register(Groupon.class, itemBuyerCityViewBinder);
        mMultiAdapter.setItems(mItems);
        rv.setAdapter(mMultiAdapter);
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && itemBuyerCityViewBinder != null) {
                    itemBuyerCityViewBinder.timerStart();
                    Log.i("onScrollStateChanged", "回调了");
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        reqSupplyStoreDyn(0);
    }

    //用户刷新的时候要刷新的接口
    public void updateReqData() {
        if (getActivity() != null) {
            reqMerchantList();
//            requestMainCnt();
            reqSupplyStoreDyn(0);
        }
    }

    private void intoGrouponInfo(String grouponId, String productId, Groupon data) {
        reqProductAgencyStores(grouponId, productId, data);
    }

    protected void intoBaseStore(String baseStoreId) {
        Intent intent = new Intent(getContext(), BaseStoreInfoActivity.class);
        intent.putExtra("baseStoreId", baseStoreId);
        startActivity(intent);
    }

    private void intoProductDetail(HomeBuyer data) {
        Intent intent = new Intent(getContext(), BaseProductDetailActivity.class);
        intent.putExtra("baseStoreId", data.getBaseStoreId());
        intent.putExtra("productId", data.getId());
        startActivity(intent);
    }

    private void intoAgencyPage(String grouponId, String productId) {
        Intent intent = new Intent(getContext(), AgencyListActivity.class);
        intent.putExtra("storeId", storeId);
        intent.putExtra("grouponId", grouponId);
        intent.putExtra("productId", productId);
        startActivity(intent);
    }

    private void intoGrouponInfoPage(String grouponId, String productId, AgencyListItem item) {
        Intent intent = new Intent(getContext(), GrouponInfoActivity.class);
        intent.putExtra("grouponId", grouponId);
        intent.putExtra("productId", productId);
        intent.putExtra("isSingle", true);
        intent.putExtra("storeId", storeId);
        intent.putExtra("agencyItem", JsonUtils.toJson(item));
        startActivity(intent);
    }

    private void intoGrouponInfoPage2(String grouponId, String productId) {
        Intent intent = new Intent(getContext(), GrouponInfoActivity.class);
        intent.putExtra("zanting", "zanting");
        intent.putExtra("grouponId", grouponId);
        intent.putExtra("productId", productId);
        intent.putExtra("isSingle", true);
        intent.putExtra("storeId", storeId);
        startActivity(intent);
    }

    /**
     * 我要买商品列表
     * 12.17
     *
     * @param pageNum
     */
    public void reqSupplyStoreDyn(int pageNum) {
        if (getActivity() == null) {
            return;
        }
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
//        RequestEntityMapSupply.setCmd("supplier/product/list");
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_PRODUCT_LIST);
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("pageNumber", pageNum);
        RequestEntityMapSupply.putParameter("hasAgent", 1);
        RequestEntityMapSupply.putParameter("pageSize", 10);
        RequestEntityMapSupply.putParameter("areaCode", cityId);
        RequestEntityMapSupply.putParameter("categoryiiiId", categoryId);
//        request(RequestEntityMapSupply, "supplier/product/list", onSupplyStoreDynRequestListener);
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_PRODUCT_LIST, onSupplyStoreDynRequestListener);
    }

    private OnRequestListener<ContentEntity<HomeBuyer>> onSupplyStoreDynRequestListener = new OnRequestListener<ContentEntity<HomeBuyer>>() {
        @Override
        public ContentEntity<HomeBuyer> jsonToObj(String responseStr) {
            return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, HomeBuyer.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            if (getActivity() == null) {
                return;
            }
            ptrFrameLayout.refreshComplete();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (getActivity() == null) {
                return;
            }
            ptrFrameLayout.refreshComplete();
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<HomeBuyer>> response, Object tag) {
            if (getActivity() == null) {
                return;
            }
            ptrFrameLayout.refreshComplete();
            ContentEntity<HomeBuyer> responseElement = response.getResponseElement();
            boolean last = responseElement.getLast();
            int number = responseElement.getNumber();
            List<HomeBuyer> content = responseElement.getContent();
            //第一页
            if (number == 0) {
                mHomeBuyers.clear();
                mItems.clear();
            }
            pageNum = number;
            boolean isGrouponList = false;
            if (content != null) {
                int size = content.size();
                for (int i = 0; i < size; i++) {
                    HomeBuyer homeBuyer = content.get(i);
                    List<Groupon> groupon = homeBuyer.getGroupon();
                    mHomeBuyers.add(homeBuyer);
                    mItems.add(homeBuyer);
                    if (groupon != null) {
                        int size1 = groupon.size();
                        if (size1 > 0) {
                            isGrouponList = true;
                        }
                        for (int j = 0; j < size1; j++) {
                            Groupon grouponItem = groupon.get(j);
                            grouponItem.setProductId(homeBuyer.getId());
                            grouponItem.setBaseStoreId(homeBuyer.getBaseStoreId());
                            grouponItem.setChargeUnit(homeBuyer.getChargeUnit());
                            if (j == size1 - 1) {
                                grouponItem.setLast(true);
                            } else {
                                grouponItem.setLast(false);
                            }
                            mItems.add(grouponItem);
                        }
                    }
                }
            }

            if (mHomeBuyers.size() == 0) {
                loadMoreDelegate.setStatusEmpty();
                loadMoreDelegate.addLoadItemOnly(mItems);
            } else {
                loadMoreDelegate.addLoadItemOnly(mItems);
                //最后一个
                if (last) {
                    loadMoreDelegate.setStatusNoMore();
                } else {
                    loadMoreDelegate.setStatusNormal();
                }
            }
            mMultiAdapter.notifyDataSetChanged();
            if (isGrouponList) {
                itemBuyerCityViewBinder.timerStart();
            } else {
                itemBuyerCityViewBinder.timerStop();

            }
        }
    };

    /**
     * 我要买拼货时,选择代办店铺列表
     * 12.95
     *
     * @param grouponId
     * @param productId
     */
    private void reqProductAgencyStores(final String grouponId, final String productId, final Groupon grouponBean) {
        if (isLockAgency) {
            return;
        }
        isLockAgency = true;
        RequestEntityMapSupply data = new RequestEntityMapSupply();
        data.setCmd(BuyerConstant.CMD_BUYER_PRODUCT_AGENT_STORES);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        data.setStoreId(BaseApplication.getInstance().getStoreId());
        data.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        data.putParameter("grouponId", grouponId);
        data.putParameter("productId", productId);
        requestBuyer(data, BuyerConstant.CMD_BUYER_PRODUCT_AGENT_STORES, new OnRequestListener<List<AgencyListItem>>() {
            @Override
            public List<AgencyListItem> jsonToObj(String responseStr) {
                return JsonUtils.fromJsonList(responseStr, AgencyListItem.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                isLockAgency = false;
                hideProgressDialog();
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                isLockAgency = false;
            }

            @Override
            public void onStart(Object tag) {
                showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<List<AgencyListItem>> response, Object tag) {
                List<AgencyListItem> responseElement = response.getResponseElement();
                hideProgressDialog();
                isLockAgency = false;
                if (responseElement != null) {
                    if (grouponId == null) {//跳转到选择哪一个代办的页面
                        if (responseElement.size() != 0) {
                            if (responseElement.size() == 1) {
                                AgencyListItem item = responseElement.get(0);
                                intoGrouponInfoPage(grouponId, productId, item);
                            } else {
                                intoAgencyPage(grouponId, productId);
                            }
                        } else {
                            Toast.makeText(PingCheJinHuoFragment.this.getContext(), "该商品未找到代办店铺信息，请刷新后重试!", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        intoGrouponInfoPage2(grouponId, productId);
                    }
                }
            }
        });
    }

    public void reqMerchantList() {
        if (getActivity() == null) {
            return;
        }
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_merchant_afterLogin);
        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_merchant_afterLogin, onMerchantRequestListener);
    }

    private OnRequestListener<List<MerChantInfo>> onMerchantRequestListener = new OnRequestListener<List<MerChantInfo>>() {
        @Override
        public List<MerChantInfo> jsonToObj(String responseStr) {
            MerchantMember merchantMember = JsonUtils.fromJson(responseStr, MerchantMember.class);
            ArrayList<String> disabledResources = null;
            List<MerChantInfo> mcis = new ArrayList<MerChantInfo>();
            if (merchantMember != null) {
                List<StaffInfo> list = merchantMember.getEmployees();
                disabledResources = merchantMember.getDisabledResources();

                if (list != null)
                    for (int i = 0; i < list.size(); i++) {
                        StaffInfo staffInfo = list.get(i);
                        if (staffInfo != null) {
                            MerChantInfo mc = staffInfo.getMerchant();
                            if (mc != null) {
                                staffInfo.setMerchant(null);

                                mc.setStaffInfo(staffInfo);
                                if (mc.isOwned()) {
                                    mc.setDisabledResources(disabledResources);
                                }
                                mcis.add(mc);
                            }
                        }
                    }

            }
            BaseApplication.getInstance().updateMerchants(mcis);
            BaseApplication.getInstance().putMerchantDisabledResources(disabledResources);
            return mcis;
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<List<MerChantInfo>> response, Object tag) {
            FragmentActivity activity = getActivity();
            if (activity != null && activity instanceof HomeActivity) {
               // ((HomeActivity) activity).updateBuyerStatus();
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (itemBuyerCityViewBinder != null)
            itemBuyerCityViewBinder.timerStop();
    }
}
